package com.dw.widget.slideshow.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.dw.widget.slideshow.db.helper.ImageDBHelper;
import com.dw.widget.slideshow.db.object.ImageData;
import com.dw.widget.slideshow.utils.log.Log;

import android.content.Context;
import android.os.FileObserver;

public class ImageFileObserver extends FileObserver {

	private final String TAG = "ImageFileObserver";
	private final ApplicationEx _APP = ApplicationEx.INSTANCE();
	
	private Context context;
	private String monitorPath;
	
	public ImageFileObserver(Context context, String path) {
		
		super(path);
		this.context = context;
		monitorPath = path;
	}

	@Override
	public void onEvent(int event, String path) {

		String fullPath = String.format("%1$s/%2$s", monitorPath, path);
		
		switch(event)
		{
			case FileObserver.MOVED_TO:
			case FileObserver.CREATE:
			{
				Log.d(context, TAG, String.format("add file %1$s", fullPath));
				
				insert(fullPath);
				break;
			}
			case FileObserver.MOVED_FROM:
			case FileObserver.DELETE:
			{
				Log.d(context, TAG, String.format("remove file %1$s", fullPath));
				
				delete(fullPath);
				break;
			}
			case FileObserver.DELETE_SELF:
			{
				break;
			}
		}
	}
	
	private void insert(String path)
	{
		if(ImageUtils.isImageFile(path) == false)
		{
			return;
		}
		
		synchronized (_APP.DB_MODIFY_LOCK) {

			File file = new File(path);
			if(file.isDirectory())     // 为文件夹
			{
				List<File> files = new ArrayList<File>();
				ImageUtils.listImageFiles(path, files);
				AppCommon.insertImages2Db(context, files.toArray(new File[0]), path);
			}
			else   // 为文件
			{
				AppCommon.insertImage2Db(null, context, file, path);
			}
		}
	}
	
	private void delete(String path)
	{
		synchronized (_APP.DB_MODIFY_LOCK) {
			
			ImageDBHelper dbHelper = new ImageDBHelper(context, _APP.DB_NAME, ImageData.class);
			String sql = String.format("DELETE FROM %1$s WHERE picture_path LIKE '%%%2$s%%'", 
					dbHelper.getTableName(), path);
			
			Log.d(context, TAG, String.format("delete sql: %1$s", sql));
			dbHelper.getWritableDatabase().execSQL(sql);
			dbHelper.getWritableDatabase().close();
		}
	}
}
